package com.wl.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class TestBlockingNIO2 {
    @Test
    public void client(){
        try {
            //获取通道
            SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));

            FileChannel inChannel = FileChannel.open(Paths.get("receive.jpg"), StandardOpenOption.READ);
            //分配指定大小的缓冲区
            ByteBuffer buf = ByteBuffer.allocate(1024);

            //读取本地文件，并发送到服务端
            while (inChannel.read(buf) != -1){
                buf.flip();
                socketChannel.write(buf);
                buf.clear();
            }

            socketChannel.shutdownOutput();

            //接受服务端的反馈
            int len = 0;
            while ((len = socketChannel.read(buf)) != -1){
                buf.flip();
                System.out.println(new String(buf.array(),0,len));
                buf.clear();
            }

            //关闭通道
            inChannel.close();
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void server(){
        try {
            //获取通道
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //绑定连接
            serverSocketChannel.bind(new InetSocketAddress(9898));
            //获取客户端连接的通道
            SocketChannel sChannel = serverSocketChannel.accept();

            FileChannel outChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);

            //分配指定大小的缓冲区
            ByteBuffer buf = ByteBuffer.allocate(1024);

            //接收客户端的数据，并保存到本地
            while (sChannel.read(buf) != -1){
                buf.flip();
                outChannel.write(buf);
                buf.clear();
            }
            buf.put("服务端接收数据成功".getBytes());
            buf.flip();
            sChannel.write(buf);

            //关闭通道
            outChannel.close();
            sChannel.close();
            serverSocketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
